﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using WebApplication2.Common;
using WebApplication2.Controllers;
using WebApplication2.DB;
using WebApplication2.Models;

namespace WebApplication2
{
    public class Job : IJob
    {
        private readonly IModel _channel;
        private readonly string _sqlconnStr= @"Server=192.168.0.173;Database=Eshop;uid=sa;pwd=sa;";
        private static List<Orders> orders = new List<Orders>();
        private static bool canWrite = true;
        private static DateTime SubmitTime = DateTime.MinValue;
        private readonly RedisHelper _redis;
        public Job()
        {
            _channel = new RabbitmqHelper().CreateConnection();
            _redis = new RedisHelper();
        }

        public void ConsumeOrder()
        {
            int index = 0;
            //_redis.Subscribe("orders", (ch, ea) =>
            //{
            //    Interlocked.Increment(ref index);
            //    Console.WriteLine($"接收消息{index}条");
            //    var HisStorck = 0;
            //    try
            //    {
            //        var order = JsonConvert.DeserializeObject<Orders>(ea.ToString());
            //        order.ID = Guid.NewGuid();
            //        if (order.SubmitTime == DateTime.MinValue)
            //        {
            //            order.SubmitTime = DateTime.Now;
            //            order.OrderNo = order.SubmitTime.ToString("yyyyMMddHHmmss") +
            //                            new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999);
            //            orders.Add(order);
            //            if (orders.Count >= 1000)
            //            {
            //                Console.WriteLine($"超过1000条写库{orders.Count}");
            //                WriteDb();
            //            }
            //            else
            //            {
            //                if (SubmitTime == DateTime.MinValue || (DateTime.Now - SubmitTime).TotalSeconds > 5)
            //                {
            //                    Console.WriteLine($"SubmitTime时间满足条件重发{SubmitTime}");
            //                    SubmitTime = DateTime.Now;
            //                    SendRetry(SubmitTime, true);
            //                }
            //            }
            //        }
            //        else
            //        {
            //            if ((DateTime.Now - order.SubmitTime).TotalSeconds > 5 && orders.Any())
            //            {
            //                Console.WriteLine($"满足5秒写库{orders.Count}");
            //                WriteDb();
            //            }
            //            else
            //            {
            //                SendRetry(order.SubmitTime, true);
            //            }
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        Console.WriteLine($"{e.Message}");
            //    }
            //});

            EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
            //启动消费者 设置为手动应答消息
            _channel.BasicConsume("orders", true, consumer);
            //接收到消息事件
            consumer.Received += (ch, ea) =>
            {
                //Interlocked.Increment(ref index);
                //Console.WriteLine($"接收消息{index}条");
                var message = Encoding.UTF8.GetString(ea.Body);
                ////确认该消息已被消费
                var order = new Orders();
                var HisStorck = 0;
                try
                {
                    order = JsonConvert.DeserializeObject<Orders>(message);
                    order.ID = Guid.NewGuid();
                    if (order.SubmitTime == DateTime.MinValue)
                    {
                        order.SubmitTime = DateTime.Now;
                        order.OrderNo = order.SubmitTime.ToString("yyyyMMddHHmmss") +
                                        new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999);
                        orders.Add(order);
                        if (orders.Count >= 1000)
                        {
                            Console.WriteLine($"超过1000条写库{orders.Count}");
                            WriteDb();
                        }
                        else
                        {
                            if (SubmitTime == DateTime.MinValue || (DateTime.Now - SubmitTime).TotalSeconds > 5)
                            {
                                Console.WriteLine($"SubmitTime时间满足条件重发{SubmitTime}");
                                SubmitTime = DateTime.Now;
                                SendRetry(SubmitTime, false);
                            }
                        }
                    }
                    else
                    {
                        if ((DateTime.Now - order.SubmitTime).TotalSeconds > 5 && orders.Any())
                        {
                            Console.WriteLine($"满足5秒写库{orders.Count}");
                            WriteDb();
                        }
                        else
                        {
                            SendRetry(order.SubmitTime, false);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"{e.Message}");
                }
            };
            //EventingBasicConsumer consumer = new EventingBasicConsumer(_channel);
            ////启动消费者 设置为手动应答消息
            //_channel.BasicConsume("orders", false, consumer);
            ////接收到消息事件
            //consumer.Received += (ch, ea) =>
            //{
            //    Console.WriteLine($"接收消息{index}条");
            //    _channel.BasicAck(ea.DeliveryTag, false);
            //    //var message = Encoding.UTF8.GetString(ea.Body);
            //    //////确认该消息已被消费
            //    //var order = new Orders();
            //    //var HisStorck = 0;
            //    //try
            //    //{
            //    //    order = JsonConvert.DeserializeObject<Orders>(message);
            //    //    order.ID = Guid.NewGuid();
            //    //    if (order.SubmitTime == DateTime.MinValue)
            //    //    {
            //    //        order.SubmitTime = DateTime.Now;
            //    //        order.OrderNo = order.SubmitTime.ToString("yyyyMMddHHmmss") +
            //    //                        new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999);
            //    //        orders.Add(order);
            //    //        if (orders.Count >= 1000)
            //    //        {
            //    //            Console.WriteLine($"超过1000条写库{orders.Count}");
            //    //            WriteDb();
            //    //        }
            //    //        else
            //    //        {
            //    //            if (SubmitTime == DateTime.MinValue || (DateTime.Now - SubmitTime).TotalSeconds > 5)
            //    //            {
            //    //                Console.WriteLine($"SubmitTime时间满足条件重发{SubmitTime}");
            //    //                SubmitTime = DateTime.Now;
            //    //                SendRetry(SubmitTime);
            //    //            }
            //    //        }
            //    //    }
            //    //    else
            //    //    {
            //    //        if ((DateTime.Now - order.SubmitTime).TotalSeconds > 5 && orders.Any())
            //    //        {
            //    //            Console.WriteLine($"满足5秒写库{orders.Count}");
            //    //            WriteDb();
            //    //        }
            //    //        else
            //    //        {
            //    //            SendRetry(order.SubmitTime);
            //    //        }
            //    //    }
            //    //}
            //    //catch (Exception e)
            //    //{
            //    //    Console.WriteLine($"{e.Message}");
            //    //}
            //    //finally
            //    //{

            //    //    _channel.BasicAck(ea.DeliveryTag, false);
            //    //}
            //};
            Console.WriteLine("消费者已启动");
        }

        void WriteDb()
        {
            using (var db = new SqlConnection(_sqlconnStr))
            {
                var goods = db.Query<Goods>("select top 1 * from Goods").FirstOrDefault();
                var command =
                    $"update Goods set Stock-={orders.Count} where id='{goods.ID}' and Stock={goods.Stock}";
                if (db.Execute(command) > 0)
                {
                    db.Execute(
                        "INSERT INTO [dbo].[Orders] ([ID],[OrderNo],[GoodsId],[HisStorck],[UserId],[SubmitTime]) VALUES (@ID,@OrderNo,@GoodsId,@HisStorck,@UserId,@SubmitTime)",
                        orders);
                    orders.RemoveAll(x => true);
                }
                else
                {
                    Console.WriteLine($"冲突重发");
                    var lastorder = orders.LastOrDefault();
                    orders.Remove(lastorder);
                    RabbitmqHelper.SendMessage(lastorder);
                }
            }
        }

        void SendRetry(DateTime retry,bool isredis)
        {
            if (orders.Any())
            {
                if (isredis)
                {
                    _redis.Publish("orders", new Orders()
                    {
                        SubmitTime = retry
                    });
                }
                else
                {
                    RabbitmqHelper.SendMessage(new Orders()
                    {
                        SubmitTime = retry
                    });
                }
            }
        }
    }
}
